﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Platform_Controller: MonoBehaviour
{
    public Transform BoundaryA, BoundaryB;
    public float moveSpeed;
    private float faceDirection,maxX,maxY,minX,minY,tempDrag;
    private Vector3 direction;
    // Start is called before the first frame update
    void Start()
    {
        faceDirection = 1;
        maxX = BoundaryA.position.x >= BoundaryB.position.x ? BoundaryA.position.x : BoundaryB.position.x;
        minX = BoundaryA.position.x < BoundaryB.position.x ? BoundaryA.position.x : BoundaryB.position.x;
        
        maxY = BoundaryA.position.y >= BoundaryB.position.y ? BoundaryA.position.y : BoundaryB.position.y;
        minY = BoundaryA.position.y < BoundaryB.position.y ? BoundaryA.position.y : BoundaryB.position.y;

        direction = new Vector3(maxX - minX, maxY - minY, 0);
        //BoundaryA.transform.SetParent(null);
        //BoundaryB.transform.SetParent(null);
        transform.position = new Vector3((maxX + minX) / 2, (maxY + minY) / 2, 0);
        //BoundaryA.transform.SetParent(transform);
        //BoundaryB.transform.SetParent(transform);


        Destroy(BoundaryA.gameObject);
        Destroy(BoundaryB.gameObject);    
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        if (transform.position.x < minX || transform.position.y < minY)
            faceDirection = 1;
        if (transform.position.x > maxX || transform.position.y > maxY)
            faceDirection = -1;
        
        transform.position = new Vector3(transform.position.x + faceDirection * Time.fixedDeltaTime * moveSpeed * direction.normalized.x,
                                         transform.position.y + faceDirection * Time.fixedDeltaTime * moveSpeed * direction.normalized.y, 0);


    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if(collision.gameObject.CompareTag("Player"))
        {
            collision.gameObject.transform.SetParent(transform);
            tempDrag= collision.gameObject.GetComponent<Rigidbody2D>().drag;
            collision.gameObject.GetComponent<Rigidbody2D>().drag = 0f;
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        collision.gameObject.transform.SetParent(null);
        collision.gameObject.GetComponent<Rigidbody2D>().drag = tempDrag;
    }

}

